<template>
  <div class="p-4">
    <el-card class="box-card" v-if="!detail_card">
      <div slot="header" class="clearfix">
        <el-form :model="listQuery" inline>
          <el-form-item>
            <el-input
              type="text"
              class="w-80"
              v-model="listQuery.keyword"
              placeholder="请输入用户编号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="success"
              size="small"
              icon="el-icon-search"
              @click="deBounceWrap(handleSearch)"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
        <div class="flex items-center mb-3">
          <el-button
            @click="handleChange(7)"
            class="mr-3 cursor-pointer"
            style="background: #cc9933; color: #fff"
            plain
            >铜盲盒</el-button
          >
          <el-button
            @click="handleChange(8)"
            class="mr-3 cursor-pointer"
            style="background: #c0c0c0; color: #fff"
            plain
            >银盲盒</el-button
          >
          <el-button
            @click="handleChange(9)"
            class="mr-3 cursor-pointer"
            style="background: #ffd700; color: #fff"
            plain
            >金盲盒</el-button
          >
        </div>
      </div>
      <el-table :data="individualData" border>
        <el-table-column prop="user_id" label="用户ID"></el-table-column>
        <el-table-column prop="user_code" label="用户编号"></el-table-column>
        <el-table-column prop="nickname" label="用户昵称"></el-table-column>
        <el-table-column prop="head_picture" label="头像">
          <template slot-scope="scope">
            <el-popover placement="right" width="220" trigger="hover">
              <img
                :src="scope.row.head_picture"
                alt=""
                style="max-width: 200px; max-height: 200px"
              />
              <img
                slot="reference"
                :src="scope.row.head_picture"
                alt=""
                style="width: 100px; height: 100px"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="set_value" label="移除投入"></el-table-column>
        <el-table-column prop="inject" label="累计投入"></el-table-column>
        <el-table-column prop="earnings" label="累计收益"></el-table-column>
        <el-table-column
          prop="output_proportion"
          label="产出比"
        ></el-table-column>
        <el-table-column label="奖池详细" width="100px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="handleClickDetail(scope.row)"
              >查看详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <cus-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.per_page"
        @pagination="getUserList"
      />
    </el-card>

    <el-card class="box-card" v-else>
      <div slot="header">
        用户{{ this.nickname }}的个人奖池列表
        <div style="float: right">
          <el-button round type="danger" @click="goback">返回</el-button>
        </div>
      </div>
      <div class="item">
        <el-button type="success" class="mb-5" @click="deBounceWrap(handleAdd)"
          >&emsp;新增&emsp;</el-button
        >
        <el-button type="danger" @click="deBounceWrap(handleDeleteAll)"
          >批量删除</el-button
        >
        <el-button type="primary" @click="deBounceWrap(handleEditAll)"
          >一键修改</el-button
        >
        <el-table
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="名称" prop="gift_name"></el-table-column>
          <el-table-column prop="price" label="价格"> </el-table-column>
          <el-table-column prop="picture" label="头像">
            <template slot-scope="scope">
              <el-popover placement="right" width="220" trigger="hover">
                <img
                  :src="scope.row.picture"
                  alt=""
                  style="max-width: 200px; max-height: 200px"
                />
                <img
                  slot="reference"
                  :src="scope.row.picture"
                  alt=""
                  style="width: 100px; height: 100px"
                />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="number" label="数量"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                plain
                @click="deBounceWrap(handleClickEdit, scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                plain
                @click="deBounceWrap(handleClickDelete, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页
                <cus-pagination
                    :total="total"
                    :page.sync="listQuery.page"
                    :limit.sync="listQuery.perPage"
                    @pagination="getList(1,jackpotType)"
                />-->
      </div>
    </el-card>
    <!-- 删除弹框
        <el-dialog
            title="确定删除吗?"
            :visible.sync="deleteDialogVisible"
            width="435px"
            >
            <span style=""><em style="font-style:normal;color:red">删除后不可恢复</em>，你还要继续吗？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="deleteDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="confirmDelete">确 定</el-button>
            </span>
        </el-dialog>
    -->
    <el-dialog
      :title="titleOptions[title] + '礼物'"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      @close="handleClear"
      width="30%"
      :before-close="handleClose"
    >
      <el-form :model="form" ref="form" :rules="rules"   label-width="120px"
       >
        <el-form-item label="选择礼物" prop="gift_id">
          <el-select v-model="form.gift_id">
            <el-option
              v-for="item in giftlistOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="数量" prop="number" >
          <el-input v-model.number="form.number" clearable></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" plain @click="handleClose">返回</el-button>
        <el-button type="primary" @click="deBounceWrap(handleSumbit, 'form')"
          >提交</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      v-dialogDrag
      title="一键修改"
      :visible.sync="dialogFormVisible2"
      @close="handleDialogClose2"
    >
      <el-form
        ref="form2"
        :model="form2"
        label-width="120px"
        style="width: 400px; margin: 0 auto"
      >
        <template v-for="(item, index) in form2Arr">
          <div :key="index">
          <el-form-item label="选择礼物"  :rules="{
              required: true,
              message: '礼物不能为空',
              trigger: 'change',
            }">
            <el-select v-model="item.gift_id">
              <el-option
                v-for="item in giftlistOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="数量"
            :prop="'form2Arr.' + index + '.number'"
            :rules="{
              required: true,
              message: '数量不能为空',
              trigger: 'blur',
            }"
          >
            <el-input v-model="item.number" placeholder="请输入数量" />
          </el-form-item>
          </div>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" plain @click="handleClose2">返回</el-button>
        <el-button type="primary" @click="deBounceWrap(handleSumbit2, 'form')"
          >提交</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  userList,
  userdetail,
  userdetailDel,
  userdetailAdd,
  userdetailEdit,
} from "@/api/blindBox/individualPool";
import { giftlist } from "@/api/blindBox";
export default {
  name: "individualPool",
  data() {
    return {
      detail_card: false,
      /*盲盒类型：7：铜；8：银；9：金*/
      box_type: 7,
      listQuery: {
        keyword: undefined,
        page: 1,
        per_page: 20,
      },
      total: 0,
      rowData: {},
      individualData: [],
      tableData: [],
      nickname: undefined,
      titleOptions: {
        add: "新增",
        edit: "编辑",
      },
      title: "add",
      detailRowData: {},
      form: {
        user_id: undefined,
        gift_id: undefined,
        number: undefined,
        gift_info: undefined,
      },
      dialogVisible: false,
      rules: {
        gift_id: [{ required: true, message: "请选择礼物", trigger: "change" }],
        number: [
          { required: true, message: "请输入礼物数量", trigger: "blur" },
        ],
      },
      //礼物列表
      giftlistOptions: [],
      //勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: "",
      //一键修改
      dialogFormVisible2: false,
      form2: {
        user_id: undefined,
        gift_id: undefined,
        number: undefined,
        gift_info: undefined,
      },
      form2Arr: [],
    };
  },
  created() {
    this.getUserList();
    this.getUserDetail();
  },
  methods: {
    handleSearch() {
      this.getUserList();
    },
    getUserList() {
      let data = {
        box_type: this.box_type,
        keyword: this.listQuery.keyword,
        page: this.listQuery.page,
        per_page: this.listQuery.per_page,
      };
      userList(data).then((res) => {
        this.individualData = res.data.list.data;
        this.total = res.data.list.total;
      });
    },
    handleChange(type) {
      this.box_type = type;
      this.getUserList();
    },
    ////////////////////////
    getUserDetail() {
      let data = { user_id: this.rowData.user_id, box_type: this.box_type };
      userdetail(data).then((res) => {
        this.tableData = JSON.parse(JSON.stringify(res.data))
        this.form2Arr = JSON.parse(JSON.stringify(res.data))
      });
    },
    handleClickDetail(row) {
      this.rowData = row;
      this.detail_card = true;
      this.nickname = row.nickname;
      this.getUserDetail();

    },
    getGiftList() {
      giftlist(this.form.pond_type).then((res) => {
        this.giftlistOptions = res.data;
      });
    },
    async handleAdd() {
      this.title = "add";
      if (this.giftlistOptions.length === 0) {
        await this.getGiftList();
      }
      this.dialogVisible = true;
    },
    handleSumbit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.title === "add") {
            let data = {
              box_type: this.box_type,
              user_id: this.rowData.user_id,
              gift_id: this.form.gift_id,
              number: this.form.number,
            };
            userdetailAdd(data).then((res) => {
              if (res.code === 200) {
                this.$message.success("操作成功");
                this.getUserDetail();
                this.getUserList();
                this.dialogVisible = false;
              } else {
              }
            });
          }
          if (this.title === "edit") {
            let formgift_info = `${this.detailRowData.id},${this.form.gift_id},${this.form.number}`;
            userdetailEdit({
              user_id: this.rowData.user_id,
              box_type: this.box_type,
              gift_info: formgift_info
            }).then((res) => {
              if (res.code === 200) {
                this.$message.success("编辑成功");
                this.getUserDetail();
                this.getUserList();
                this.dialogVisible = false;
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    goback() {
      this.detail_card = false;
    },
    async handleClickEdit(row) {
      this.title = "edit";
      this.detailRowData = row;
      await this.getGiftList();
      // this.form.user_id = this.rowData.user_id;
      this.form.gift_id = row.gift_id;
      this.form.number = row.number;
      // this.form.gift_info = `${this.detailRowData.id},${this.detailRowData.gift_id},${this.detailRowData.number}`;
      this.dialogVisible = true;
    },

    handleClickDelete(row) {
      this.$confirm("确认删除!?此步骤无法恢复。", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = {
            ids: row.id,
          };
          userdetailDel(data).then((res) => {
            if (res.code === 200) {
              this.getUserDetail();
              this.$message({
                type: "success",
                message: "删除成功",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleClose() {
      this.dialogVisible = false;
    },
    handleClear() {
      this.$refs["form"].resetFields();
      this.form = {
        user_id: undefined,
        gift_id: undefined,
        number: undefined,
        gift_info: undefined,
      };
    },
    //一键删除
    handleDeleteAll() {
      if (this.multipleSelection.length) {
        /* 存在勾选数据 */ const ids = this.multipleSelection.reduce(
          (pre, currRow) => {
            pre += `${currRow.id},`;
            return pre;
          },
          ""
        );
        userdetailDel({ ids })
          .then(() => this.$message.success("删除成功！"))
          .catch(console.error)
          .finally(() => /* 刷新数据 */ {
            this.multipleSelection = [];
            this.getUserDetail();
          });
      } /* 不存在勾选数据 */ else {
        this.$message.warning("请勾选要删除的数据！");
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //一键修改
    async handleEditAll() {
      this.dialogFormVisible2 = true;
      await this.getGiftList();
      this.getUserList();
    },
    handleDialogClose2() {
      if (this.$refs["form2"]) {
        this.$refs["form2"].clearValidate(); // 清除整个表单的校验
      }
      this.form2 = {
        user_id: undefined,
        gift_id: undefined,
        number: undefined,
        gift_info: undefined,
      };
    },
    handleClose2() {
      this.dialogFormVisible2 = false;
    },
    handleSumbit2() {
      let gift_info = this.form2Arr.reduce((pre, curr) => {
        pre += `${curr.id},${curr.gift_id},${curr.number};`;
        return pre;
      }, "");
      userdetailEdit({
        user_id: this.rowData.user_id,
        box_type: this.box_type,
        gift_info,
      }).then((res) => {
        if (res.code === 200) {
          this.$message.success("编辑成功");
          this.getUserDetail();
          this.getUserList();
          this.dialogFormVisible2 = false;
        }
      });
    },
  },
};
</script>

<style scoped>
</style>
